<?php if ( ! defined('APPPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
*/
include_once APPPATH.'modules/social/OAuth_Renren.php';
class renren_api{

	private $vendor='renren';
	private $pz;
	protected $oauth;
	protected $client;
	protected $info;
	function __construct(){
		$socialapis = load_api('setting')->getSetting('socialapi');
		$this->info = $socialapis['renren'];
		$this->pz = &get_instance();
	}

	function getloginpage($state=NULL,$display=NULL){
		return "https://graph.renren.com/oauth/authorize?client_id=".$this->info['appkey']."&redirect_uri=".$this->info['callback']."&response_type=code";
	}

	function get_accesstoken(){
		if(isset($_REQUEST['code'])){
			$url = "https://graph.renren.com/oauth/token?client_id=" . $this->info['appkey']
			. "&client_secret=" . $this->info['appsecret']
			. "&redirect_uri=".$this->info['callback']
			. "&grant_type=authorization_code&code=".$_REQUEST['code'];
			$json = json_decode ( get_contents($url,3,false,0) );
			if($json){
				$this->info['access_token'] = $json->access_token;
				$url = "https://graph.renren.com/renren_api/session_key?oauth_token=" . $json->access_token;
				$temp_info = json_decode(get_contents($url,3,false,0),true);
				if($temp_info)
				{
					$this->info['session_secret'] = $temp_info['renren_token']['session_secret'];
					$this->info['expires_in'] = $temp_info['renren_token']['expires_in'];
					$this->info['session_key'] = $temp_info['renren_token']['session_key'];
					$this->info['oauth_token'] = $temp_info['oauth_token'];
					$this->info['user_id'] = $temp_info['user']['id'];
				}
				return $this->info;
			}
		}
		return NULL;
	}

	function get_userinfo(){
		if(isset($this->info['user_id'])){
			$this->oauth=new RenRenOauth($this->info['appkey'], $this->info['appsecret'],$this->info['session_key']);
			$temp_user=$this->oauth->users('getInfo',array('uids'=>$this->info['user_id']));
			if($temp_user && isset($temp_user[0]['uid'])){
				$userinfo = array();
				$userinfo['uid'] = $temp_user[0]['uid'];
				$userinfo['screen_name'] = $temp_user[0]['name'];
				$userinfo['name'] = $temp_user[0]['name'];
				$userinfo['avatar'] = $temp_user[0]['tinyurl'];
				$userinfo['location'] = $temp_user[0]['hometown_location']['province'].$temp_user[0]['hometown_location']['city'];
				$userinfo['description'] = '';
				$userinfo['url'] = '';
				if($temp_user[0]['sex']=='1'){
					$userinfo['gender'] = 'male';
				}elseif ($temp_user[0]['sex']=='0'){
					$userinfo['gender'] = 'female';
				}else{
					$userinfo['gender'] = 'none';
				}
				return $userinfo;
			}
		}
		return null;
	}
}
